﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace Guest_room
{
    class DB
    {
        public static SqlConnection cn;
        public static SqlConnection GetCn()
        {
            //string mystr = "server=.;database=Guest_room;integrated security=true";
            string mystr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Guest_room.mdf;Integrated Security=True";
            if (cn==null||cn.State==ConnectionState.Closed)
            {
                cn = new SqlConnection(mystr);
                cn.Open();
            }
            return cn;
        }
        public static DataTable GetDataSet(string sql)//查询数据库
        {
            sql = sql.Trim();
            SqlCommand cmd = new SqlCommand(sql, cn);//执行sql语句
            SqlDataAdapter da = new SqlDataAdapter(cmd);//将执行结果保存在适配器中
            DataSet ds = new DataSet();//创建数据集
            da.Fill(ds);//将适配器中的结果填充到数据集
            return ds.Tables[0];
        }
        public static Boolean sqlEx(string sql)//对数据库的添加修改，删除操作
        {
            SqlCommand cmd=new SqlCommand(sql, cn);
            try
            {
                cmd.ExecuteNonQuery();//同步更新数据源
                cn.Close();
            }
            catch (SqlException ex)
            {
                cn.Close() ;
                MessageBox.Show("执行失败\n" + ex.Message.ToString());
                return false;
            }
            return true;
        }
    }
}
